package com.thwj.project.app.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thwj.common.exception.ServiceException;
import com.thwj.common.utils.StringUtils;
import com.thwj.common.utils.WzDateUtil;
import com.thwj.framework.security.LoginUser;
import com.thwj.project.app.api.param.ActivitySignUpParam;
import com.thwj.project.app.api.param.ChatRoomParam;
import com.thwj.project.app.api.vo.ActivityUserSignUpVo;
import com.thwj.project.app.api.vo.ChatRoomMessageAddressVo;
import com.thwj.project.app.api.vo.ChatroomContentVo;
import com.thwj.project.app.api.vo.ChatroomVo;
import com.thwj.project.app.event.ActivityCreateSuccessEvent;
import com.thwj.project.biz.domain.Activity;
import com.thwj.project.biz.domain.ActivityChatroom;
import com.thwj.project.biz.domain.ActivitySignup;
import com.thwj.project.biz.domain.User;
import com.thwj.project.biz.enums.ActivitySignUpStatusEnum;
import com.thwj.project.biz.enums.AuditStatusEnum;
import com.thwj.project.biz.enums.ChatRoomMessageTypeEnum;
import com.thwj.project.biz.service.IActivityChatroomService;
import com.thwj.project.biz.service.IActivityService;
import com.thwj.project.biz.service.IActivitySignupService;
import com.thwj.project.biz.service.IUserService;
import com.thwj.project.push.enums.PushTemplateEnumNew;
import com.thwj.project.push.event.WxMpAdminMessageEvent;
import com.thwj.project.secCheck.SecCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class AppChatRoomService {

    @Autowired
    SecCheckUtil secCheckUtil;
    @Autowired
    IActivityChatroomService activityChatroomService;
    @Autowired
    IUserService userService;
    @Autowired
    IActivityService activityService;
    @Autowired
    IActivitySignupService activitySignupService;
    @Autowired
    UserInfoResolver userInfoResolver;
    @Autowired
    AppActivityService appActivityService;
    @Autowired
    ApplicationEventPublisher applicationEventPublisher;

    public void commitChatContent(ChatRoomParam chatRoomParam, LoginUser loginUser) {
        if(chatRoomParam.getActivityId() == null || StringUtils.isEmpty(chatRoomParam.getContent())) {
            throw new ServiceException("参数缺少");
        }
        if(chatRoomParam.getContent().length() > 100) {
            throw new ServiceException("字数超出限制");
        }
        //先进性文字内容的安全识别
        boolean isSecurity = secCheckUtil.checkContentSecurity(chatRoomParam.getContent());
        if(!isSecurity) {
            log.error("【聊天室内容异常】 信息：{} user:{}",chatRoomParam, loginUser);
            throw new ServiceException("发言内容不合规，请文明用语");
        }
        // 读取当前用户
        User currentUer = userService.getById(loginUser.getUserId());
        // 读取活动
        Activity activity = activityService.getById(chatRoomParam.getActivityId());

        ActivityChatroom insert = new ActivityChatroom();
        insert.setUserId(loginUser.getUserId());
        insert.setActivityId(activity.getId());
        insert.setMessageContent(chatRoomParam.getContent());
        insert.setMessageType(ChatRoomMessageTypeEnum.word.getValue());
        insert.setCreateDate(new Date());
        insert.setStatus(AuditStatusEnum.auditing_success.getValue());
        // 用户角色
        if (currentUer.getOfficeUser()!= null && currentUer.getOfficeUser()) {
            insert.setUserType(1);
        }else if(currentUer.getId().compareTo(activity.getUserId()) == 0) {
            insert.setUserType(2);
        }else {
            insert.setUserType(3);
        }
        activityChatroomService.save(insert);
    }

    public ChatroomVo getChatroomVoConfig(Long activityId, LoginUser loginUser) {
        // 读取当前用户
        User currentUer = userService.getById(loginUser.getUserId());
        // 读取活动
        Activity activity = activityService.getById(activityId);

        // 读取当前聊天室配置信息
        ChatroomVo chatroomVo = new ChatroomVo();
        chatroomVo.setRoomName(activity.getTitle());
        chatroomVo.setActivityId(activity.getId());

        // 用户角色
        if (currentUer.getOfficeUser()!= null && currentUer.getOfficeUser()) {
            chatroomVo.setUserType(1);
        }else if(currentUer.getId().compareTo(activity.getUserId()) == 0) {
            chatroomVo.setUserType(2);
        }else {
            chatroomVo.setUserType(3);
        }
        // 暂时固定 每次读取都是呼叫客服的状态
        chatroomVo.setCallKeFuBtn(1);
        // 读取报名人信息
        List<ActivitySignup> signupList = activitySignupService.list(new QueryWrapper<ActivitySignup>()
                .eq("activity_id", activityId)
                .eq("status", ActivitySignUpStatusEnum.sign_up_ed.getValue())
                .orderByAsc("pay_date"));
        if (!CollectionUtils.isEmpty(signupList)) {
            List<ActivityUserSignUpVo> userSignUpVoList  = signupList.stream().map(item->{
                ActivityUserSignUpVo signUpVo = new ActivityUserSignUpVo();
                signUpVo.setUserId(item.getUserId());
                return signUpVo;
            }).collect(Collectors.toList());
            // 统一更新 读取最新数据
            userInfoResolver.resolve(userSignUpVoList,ActivityUserSignUpVo::getUserId,(ActivityUserSignUpVo obj, String nickName,String headPic, Boolean officer)->{
                obj.setNickname(nickName);
                obj.setHeadPic(headPic);
                if (officer!= null && officer) {
                    obj.setUserType(1);
                }else if(obj.getUserId().compareTo(activity.getUserId()) == 0) {
                    obj.setUserType(2);
                }else {
                    obj.setUserType(3);
                }
            });
            chatroomVo.setUserSignUpVoList(userSignUpVoList);
        }

        for (int i = 0; i < signupList.size(); i++) {
            ActivitySignup signup = signupList.get(0);
            if(signup.getUserId().compareTo(currentUer.getId()) ==0 && signup.getSettleDate() == null) {
                chatroomVo.setConfirmBtn(1);
                break;
            }
            // 费用已经确认
            if(signup.getUserId().compareTo(currentUer.getId()) ==0 && signup.getSettleDate() != null) {
                chatroomVo.setConfirmBtn(2);
                break;
            }
        }
        return chatroomVo;
    }

    public List<ChatroomContentVo> getChatroomContentVoList(Long activityId, LoginUser loginUser) {

        List<ActivityChatroom> chatroomList = activityChatroomService.list(
                new QueryWrapper<ActivityChatroom>()
                .eq("activity_id", activityId));

        List<ChatroomContentVo> contentVoList = new ArrayList<>();
        for (int i = 0; i < chatroomList.size(); i++) {
            contentVoList.add(convert(chatroomList.get(i),loginUser));
        }
        // 统一更新 读取最新数据
        userInfoResolver.resolve(contentVoList,ChatroomContentVo::getUserId,(ChatroomContentVo obj, String nickName, String headPic, Integer gender,String signature,String phone,String wechat)->{
            obj.setUserNickName(nickName);
            obj.setUserHeadPic(headPic);
        });

        return contentVoList;
    }

    private ChatroomContentVo convert(ActivityChatroom activityChatroom,LoginUser loginUser) {
        ChatroomContentVo chatroomContentVo = new ChatroomContentVo();
        chatroomContentVo.setId(activityChatroom.getId());
        chatroomContentVo.setMessageType(activityChatroom.getMessageType());
        chatroomContentVo.setMessageContent(activityChatroom.getMessageContent());
        chatroomContentVo.setCreateDate(WzDateUtil.getShortTime(activityChatroom.getCreateDate()));
        chatroomContentVo.setUserType(activityChatroom.getUserType());
        chatroomContentVo.setUserId(activityChatroom.getUserId());
        if(loginUser!= null && activityChatroom.getUserId().compareTo(loginUser.getUserId()) ==0) {
            chatroomContentVo.setMyself(true);
        }
        // 加工颜色
        if (activityChatroom.getMessageType() == ChatRoomMessageTypeEnum.address.getValue()){
            chatroomContentVo.setAddressVo(JSON.parseObject(activityChatroom.getExtralJson(), ChatRoomMessageAddressVo.class));
        }

        return chatroomContentVo;
    }

    public void commitCallKefu(ChatRoomParam chatRoomParam, LoginUser loginUser) {

        ActivityChatroom insert = new ActivityChatroom();
        insert.setUserId(loginUser.getUserId());
        insert.setActivityId(chatRoomParam.getActivityId());
        insert.setMessageContent("已呼叫客服，客服正在前来...");
        insert.setMessageType(ChatRoomMessageTypeEnum.word.getValue());
        insert.setCreateDate(new Date());
        insert.setStatus(AuditStatusEnum.auditing_success.getValue());
        insert.setUserType(3);

        activityChatroomService.save(insert);

        User user = userService.getById(loginUser.getUserId());

        Activity activity = activityService.getById(chatRoomParam.getActivityId());

        // 发送微信通知给审核人员
        applicationEventPublisher.publishEvent(WxMpAdminMessageEvent.builder()
                .pushTemplateEnum(PushTemplateEnumNew.KEFU_ORDER)
                .miniAppPath("pages/detail/detail?activityId=" + chatRoomParam.getActivityId())
                .templateDataList(PushTemplateEnumNew.KEFU_ORDER(
                        user.getUserNickName() + "呼叫客服",
                        user.getPhone(),
                        activity.getTitle()
                        )
                ).build()
        );
    }

    public void commitUser2Confirm(ChatRoomParam chatRoomParam, LoginUser loginUser) {

        ActivitySignUpParam signUpParam = new ActivitySignUpParam();
        signUpParam.setActivityId(chatRoomParam.getActivityId());
        appActivityService.commitUserActivitySignUpFee(signUpParam, loginUser);

        ActivityChatroom insert = new ActivityChatroom();
        insert.setUserId(loginUser.getUserId());
        insert.setActivityId(chatRoomParam.getActivityId());
        insert.setMessageContent("我已确认到店，费用将结算给组局人");
        insert.setMessageType(ChatRoomMessageTypeEnum.word.getValue());
        insert.setCreateDate(new Date());
        insert.setStatus(AuditStatusEnum.auditing_success.getValue());
        insert.setUserType(3);
        activityChatroomService.save(insert);

    }


    @Async
    @EventListener
    public void initActivityChatRoomMessage(ActivityCreateSuccessEvent event) {
        // 初始化 两聊
        ActivityChatroom insert1 = new ActivityChatroom();
        insert1.setUserId(event.getActivity().getUserId());
        insert1.setActivityId(event.getActivity().getId());
        insert1.setMessageContent("欢迎参加本场活动，本场活动将于" + WzDateUtil.date2String(event.getActivity().getStartDate(), WzDateUtil.TIME_FORMAT_M)
                +"开始，请上车的小伙伴提前到场，祝大家玩的开心~"
        );
        insert1.setMessageType(ChatRoomMessageTypeEnum.word.getValue());
        insert1.setCreateDate(new Date());
        insert1.setUserType(1);
        insert1.setStatus(AuditStatusEnum.auditing_success.getValue());
        activityChatroomService.save(insert1);


        // 初始化 两聊
        ActivityChatroom insert2 = new ActivityChatroom();
        ChatRoomMessageAddressVo addressVo = new ChatRoomMessageAddressVo();
        addressVo.setAddress(event.getActivity().getAddress());
        addressVo.setLocationName(event.getActivity().getLocationName());
        addressVo.setLatitude(event.getActivity().getLatitude());
        addressVo.setLongitude(event.getActivity().getLongitude());

        insert2.setExtralJson(JSON.toJSONString(addressVo));
        insert2.setUserId(event.getActivity().getUserId());
        insert2.setActivityId(event.getActivity().getId());
        insert2.setMessageType(ChatRoomMessageTypeEnum.address.getValue());
        insert2.setCreateDate(new Date());
        insert2.setUserType(1);
        insert2.setStatus(AuditStatusEnum.auditing_success.getValue());
        activityChatroomService.save(insert2);

    }
}
